package com.imooc.mq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 构建发布订阅模式的生产者，发送消息
 */
public class PubSubProducer {
    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("imooc");
        connectionFactory.setPassword("imooc");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 创建交换机
        /*
            (String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)

            exchange: 交换机名称
            type:
                fanout 广播模式，发布订阅，把消息发送给所有的绑定的队列
                direct 定向投递模式，把消息发送给指定“routing key”的队列
                topic 通配符模式，把消息发送给符合的“routing pattern”的队列
                headers 使用率不多，参数匹配
            durable: 是否持久化
            autoDelete: 是否自动删除
            internal: 内部意思 true：表示当前exchange是rabbitmq内部使用的，用户创建的队列不会消费该类型交换机下的消息，所以一般使用false
            arguments:
         */
        String fanout_exchange = "fanout_exchange";
        channel.exchangeDeclare(fanout_exchange, BuiltinExchangeType.FANOUT,
                true, false, false, null);

        // 定义两个队列
        String fanout_queue_a = "fanout_queue_a";
        String fanout_queue_b = "fanout_queue_b";
        channel.queueDeclare(fanout_queue_a, true, false, false, null);
        channel.queueDeclare(fanout_queue_b, true, false, false, null);

        // 绑定交换机和队列
        channel.queueBind(fanout_queue_a, fanout_exchange, "");
        channel.queueBind(fanout_queue_b, fanout_exchange, "");


        for (int i = 0; i < 100; i++) {
            String msg = "hello world 开始任务 [" + i + "]";
            channel.basicPublish(fanout_exchange, "", null, msg.getBytes());
        }

        channel.close();
        connection.close();
    }
}
